/*
 * Copyright (c) 2020
 * User:Palo
 * File:HiDBUtils.java
 * Date:2020/12/26
 */

package com.iceframework.hiapp.core.utils;

import ohos.app.Context;
import ohos.data.DatabaseHelper;
import ohos.data.rdb.*;
import ohos.data.resultset.ResultSet;

import java.util.List;

/**
 *
 */
public class HiDBUtils {

    private static final RdbOpenCallback callback;

    private static final String DB_FILE = "hiapp.db";

    static {
        callback = new RdbOpenCallback() {
            @Override
            public void onUpgrade(RdbStore rdbStore, int i, int i1) {
                HiLogUtils.info("db upgrade.");
            }
            @Override
            public void onCreate(RdbStore store) {
                HiLogUtils.info("db init.");
                // 初始化应用数据库
                store.executeSql("create table if not exists test (id integer primary key autoincrement, name TEXT NOT NULL, age INTEGER, salary REAL)");
                HiLogUtils.info("db init end.");
            }
        };
    }

    public static RdbStore getRdbStore(Context context){
        StoreConfig config = StoreConfig.newDefaultConfig(DB_FILE);
        DatabaseHelper helper = new DatabaseHelper(context);
        RdbStore store = helper.getRdbStore(config, 1, callback, null);
        return store;
    }

    public static void executeSQL(RdbStore store, String sql, String[] params){
        store.executeSql(sql);
    }

    public static long insertOneRowData(RdbStore store, String tableName, ValuesBucket values){
        return store.insert(tableName, values);
    }

    public static List<Long> insertBatchData(RdbStore store, String tableName, List<ValuesBucket> values, RdbStore.ConflictResolution conflictResolution){
        return store.batchInsertOrThrowException(tableName, values, conflictResolution);
    }

    public static ResultSet query(RdbStore store, String sql, String[] params){
        ResultSet resultSet = store.querySql(sql, params);
        return resultSet;
    }
}
